<?php 
global $_GPC, $_W;
$cfg = $this->module['config'];
$shopid=check_right(0);
if(!$shopid)message("请先选择需要管理的店铺",$this->createWebUrl('shop'),'error');
$shop=pdo_fetch("SELECT * FROM ".tablename('j_hmoney_group')." WHERE weid = '{$_W['uniacid']}' and id='".$shopid."'");

$operation = !empty($_GPC['op']) ? $_GPC['op'] : 'categorydisplay';
load()->func('tpl');
if ($operation == 'categorydisplay') {
	$category = pdo_fetchall("SELECT * FROM " . tablename('j_hmoney_goodcategory') . " WHERE weid = '{$_W['uniacid']}' and groupid ='".$shopid."' order by  displayorder asc, id desc");

	$cooklist = pdo_fetchall("SELECT * FROM ".tablename('j_hmoney_cookprint')." WHERE weid = '{$_W['uniacid']}' and groupid='".$shopid."' order by id desc ");
    $shoplist=pdo_fetchall("SELECT id,companyname FROM ".tablename('j_hmoney_group')." WHERE weid = '{$_W['uniacid']}' and id<>".$shopid." order by id desc ");
	
} elseif ($operation == 'categorypost') {
	$id = intval($_GPC['id']);
	if (empty($_GPC['title']))die(json_encode(array("success"=>false,"msg"=>"抱歉，请输入分类名称！")));
	$data = array(
		'weid' => $_W['uniacid'], 
		'title' => $_GPC['title'], 
		'displayorder' => intval($_GPC['displayorder']), 
		'status' => intval($_GPC['status']), 
		'groupid' => intval($shopid), 
	);
	if (!empty($id)) {
		pdo_update('j_hmoney_goodcategory', $data, array('id' => $id));
	} else {
		pdo_insert('j_hmoney_goodcategory', $data);
	}
	die(json_encode(array("success"=>true,"item"=>$item)));

} elseif ($operation == 'copypcate') {
    $id=intval($_GPC["id"]);
    if($shopid==$id)die(json_encode(array("success"=>false,"msg"=>"不能复制到相同店铺中")));
    $category = pdo_fetchall("SELECT * FROM " . tablename('j_hmoney_goodcategory') . " WHERE weid = '{$_W['uniacid']}' and groupid ='".$shopid."' order by  displayorder asc, id desc");
    foreach($category as $row){
        $data=array(
            'weid' => $row['weid'],
            'title' => $row['title'],
            'displayorder' => intval($row['displayorder']),
            'status' => intval($row['status']),
            'groupid' => intval($id),
        );
        pdo_insert("j_hmoney_goodcategory",$data);
    }
    die(json_encode(array("success"=>true)));

} elseif ($operation == 'categorydelete') {
	$id = intval($_GPC['id']);
	$category = pdo_fetch("SELECT id FROM " . tablename('j_hmoney_goodcategory') . " WHERE id = '$id'");
	if (empty($category)) {
		message('抱歉，分类不存在或是已经被删除！', $this -> createWebUrl('goods'), 'error');
	}
    pdo_delete('j_hmoney_goods', array('pcate' => $id));
	pdo_delete('j_hmoney_goodcategory', array('id' => $id));
	message('删除成功！', $this -> createWebUrl('goods'), 'success');
	
} elseif ($operation == 'changecateorder') {
	foreach($_GPC['displayorder'] as $index=>$row){
		pdo_update('j_hmoney_goodcategory',array("displayorder"=>$row),array("id"=>$index));
	}
	die(json_encode(array("success"=>true)));
	
} elseif ($operation == 'getcate') {
	$id=intval($_GPC['id']);
	if($id==0){
		$item=pdo_fetchcolumn("SELECT max(displayorder) FROM ".tablename('j_hmoney_goodcategory')." WHERE groupid = :id ",array(':id'=>$shopid));
		die(json_encode(array("success"=>true,"num"=>$item+1)));
	}else{
		$item=pdo_fetch("SELECT * FROM ".tablename('j_hmoney_goodcategory')." WHERE id = :id ",array(':id'=>$id));
		die(json_encode(array("success"=>true,"item"=>$item)));
	}
	

} elseif ($operation == 'display') {
	if (checksubmit('hole_up')) {
		$idAry=$_GPC['goodid'];
		if(count($idAry)==0)message("请选择商品");
		pdo_update('j_hmoney_goods', array("status"=>1), " id in (".implode(",",$idAry).")");
		message('更新成功！', $this->createWebUrl('goods',array('op'=>'display')), 'success');
	}elseif(checksubmit('hole_down')){
		$idAry=$_GPC['goodid'];
		if(count($idAry)==0)message("请选择商品");
		pdo_update('j_hmoney_goods', array("status"=>0), " id in (".implode(",",$idAry).")");
		message('更新成功！', $this->createWebUrl('goods',array('op'=>'display')), 'success');
	}elseif(checksubmit('hole_cate')){
		$idAry=$_GPC['goodid'];
		if(count($idAry)==0)message("请选择商品");
		$pcate=intval($_GPC['pcate']);
		pdo_update('j_hmoney_goods', array("pcate"=>$pcate), " id in (".implode(",",$idAry).")");
		message('更新成功！', $this->createWebUrl('goods',array('op'=>'display')), 'success');
	}
	
	$cooklist = pdo_fetchall("SELECT id,title FROM ".tablename('j_hmoney_cookprint')." WHERE weid = '{$_W['uniacid']}' and groupid='".$shopid."' order by id desc ");
	$cookary=array();
	foreach($cooklist as $row){
		$cookary[$row['id']]=$row['title'];
	}
	
	$pindex = max(1, intval($_GPC['page']));
	$psize = 10;
	$condition = " and groupid ='".$shopid."' ";
	if (isset($_GPC['keyword']))$condition .= " and (title like '%" . $_GPC['keyword'] . "%' or goodsn like '%" . $_GPC['keyword'] . "%')";
	if ($_GPC['pcate']!="")$condition .= " and pcate = '" . $_GPC['pcate'] . "' ";
	if ($_GPC['status1'])$condition .= " and status = '" . ($_GPC['status1']-1) . "' ";
	if($_GPC['shorttitle'])$condition = " and groupid ='".$shopid."' and CHAR_LENGTH(  `title` ) != LENGTH(  `shorttitle` )  ";
	$list = pdo_fetchall("SELECT * FROM ".tablename('j_hmoney_goods')." WHERE weid = '{$_W['uniacid']}' $condition order by recommend desc,displayorder asc, id desc  LIMIT " . ($pindex - 1) * $psize . ',' . $psize);

	$total = pdo_fetchcolumn('SELECT COUNT(*) FROM ' . tablename('j_hmoney_goods') . " WHERE weid = '{$_W['uniacid']}' $condition");
	$pageall= $total <= $psize ? 1 : $total % $psize ? $total / $psize+1 : $total / $psize;
	$category = pdo_fetchall("SELECT * FROM " . tablename('j_hmoney_goodcategory') . " WHERE weid = '{$_W['uniacid']}' and groupid='".$shopid."' order by parentid asc, displayorder asc,id desc");
	$cateAry = array();
	foreach ($category as $row) {
		$cateAry[$row['id']] = $row['title'];
	}
	$cateAry[0]="未分类";
    $shoplist=pdo_fetchall("SELECT id,companyname FROM ".tablename('j_hmoney_group')." WHERE weid = '{$_W['uniacid']}' and id<>".$shopid." order by id desc ");
	
} elseif ($operation == 'getgoods') {
	$id = intval($_GPC['id']);
	if(empty($id))die(json_encode(array("success"=>false,"msg"=>"请选择商品")));
	$item=pdo_fetch("SELECT * FROM ".tablename('j_hmoney_goods')." WHERE id = :id ",array(':id'=>$id));
	if($item['thumb'])$item['thumb2']=tomedia($item['thumb']);
	die(json_encode(array("success"=>true,"item"=>$item)));
	
} elseif ($operation == 'post') {
	$id = intval($_GPC['id']);
	$shorttitle=$_GPC['shorttitle'];
	if($_GPC['title'] && !$shorttitle){
		$array = array();
		for($i=0; $i<mb_strlen($_GPC['title']);$i++)  {
			$array[] = getFirstCharter(mb_substr($_GPC['title'], $i, 1, 'utf-8'));  
		}
		$shorttitle=implode("",$array);
	}
	$data = array(
		'weid' => $_W['uniacid'], 
		'title' => $_GPC['title'], 
		'groupid' => intval($shopid), 
		'pcate' => intval($_GPC['pcate']), 
		'goodsn' => $_GPC['goodsn'], 
		'store' => intval($_GPC['store']),
		'thumb' => $_GPC['thumb'],
        'taste' => $_GPC['taste'],
		'marketprice' => $this->_2money(($_GPC['marketprice']*100)), 
		'productprice' => $this->_2money(($_GPC['productprice']*100)), 
		'memberprice' => $this->_2money(($_GPC['memberprice']*100)), 
		'unitname' => $_GPC['unitname'],
		'status' => intval($_GPC['status']),
		'recommend' => intval($_GPC['recommend']),
		'shorttitle' =>$shorttitle,
		'cooker' =>intval($_GPC['goodcooker']),
		'createtime' => TIMESTAMP, 
	);
	if (!empty($id)) {
		unset($data['createtime']);
		pdo_update('j_hmoney_goods', $data, array('id' => $id));
	} else {
		pdo_insert('j_hmoney_goods', $data);
	}
	die(json_encode(array("success"=>true,"item"=>$item)));

} elseif ($operation == 'copygood') {
    $id=intval($_GPC["id"]);
    if($shopid==$id)die(json_encode(array("success"=>false,"msg"=>"不能复制到相同店铺中")));
    $category = pdo_fetchall("SELECT * FROM " . tablename('j_hmoney_goodcategory') . " WHERE weid = '{$_W['uniacid']}' and groupid ='".$id."' order by  displayorder asc, id desc");
    $cateNewAry=array();
    $cateAry=array();
    foreach($category as $row) {
        $cateAry[$row['title']]=$row['id'];
    }
    $categoryold = pdo_fetchall("SELECT * FROM " . tablename('j_hmoney_goodcategory') . " WHERE weid = '{$_W['uniacid']}' and groupid ='".$shopid."' order by  displayorder asc, id desc");
    foreach($categoryold as $row) {
        $cateNewAry[$row['id']]=$cateAry[$row['title']];
    }
    $goodlist = pdo_fetchall("SELECT * FROM " . tablename('j_hmoney_goods') . " WHERE weid = '{$_W['uniacid']}' and groupid ='".$shopid."' order by id desc");
    foreach($goodlist as $row){
        $data=array(
            'weid' => $row['weid'],
            'title' => $row['title'],
            'groupid' => intval($id),
            'pcate' => intval($cateNewAry[$row['pcate']]),
            'goodsn' => $row['goodsn'],
            'store' => intval($row['store']),
            'thumb' => $row['thumb'],
            'marketprice' => $row['marketprice'],
            'productprice' => $row['productprice'],
            'memberprice' => $row['memberprice'],
            'unitname' => $row['unitname'],
            'status' => intval($row['status']),
            'recommend' => intval($row['recommend']),
            'shorttitle' =>$row['shorttitle'],
            'cooker' =>0,
            'createtime' => TIMESTAMP,
        );
        pdo_insert("j_hmoney_goods",$data);
    }
    die(json_encode(array("success"=>true)));

} elseif ($operation == 'delete') {
	$id = intval($_GPC['id']);
	$item = pdo_fetch("SELECT id FROM " . tablename('j_hmoney_goods') . " WHERE id = '$id'");
	if($item)pdo_delete('j_hmoney_goods', array('id' => $id));
	message('删除成功！', $this -> createWebUrl('goods'), 'success');
	
}elseif ($operation == 'uploadfile') {
	load()->func('file');
	$dir_url='../attachment/j_hmoney/temp/'.$_W['uniacid']."/";
	mkdirs($dir_url);
	if ($_FILES["batchoperationfile"]["name"]){
		if(file_exists($dir_url."temp.csv"))@unlink ($dir_url."temp.xls");
		move_uploaded_file($_FILES["batchoperationfile"]["tmp_name"],$dir_url."temp.xls");
	}
	die(json_encode(array('success'=>true)));
	
}elseif ($operation == 'dealxls') {
	require "../framework/library/phpexcel/PHPExcel.php";
	$filePath='../attachment/j_hmoney/temp/'.$_W['uniacid']."/temp.xls";
	if(!file_exists($filePath))die(json_encode(array('success'=>false,'msg'=>"文件不存在")));
	$objPHPExcel = new PHPExcel();
	$PHPReader = new PHPExcel_Reader_Excel5(); 
	$PHPExcel = $PHPReader->load($filePath);
	$currentSheet = $PHPExcel->getSheet(0); 
	$allColumn = 11;
	$allRow = $currentSheet->getHighestRow();
	$arr = array(1 => 'A', 2 => 'B', 3 => 'C', 4 => 'D', 5 => 'E', 6 => 'F', 7 => 'G', 8 => 'H', 9 => 'I', 10 => 'J', 11 => 'K', 12 => 'L', 13 => 'M', 14 => 'N', 15 => 'O', 16 => 'P', 17 => 'Q', 18 => 'R', 19 => 'S', 20 => 'T', 21 => 'U', 22 => 'V', 23 => 'W', 24 => 'X', 25 => 'Y', 26 => 'Z');
	$list=array();
	for($currentRow = 2;$currentRow <= $allRow;$currentRow++){ 
		$temp=array();
		for($column = 0; $column<$allColumn; $column++){ 
			$val = $currentSheet->getCellByColumnAndRow($column,$currentRow)->getValue();
			if($column == 4 || $column == 5 || $column == 7)$val=$this->_2money(($val*100));
			array_push($temp,strval($val));
		}
		$list[]=$temp;
	}
	die(json_encode(array('success'=>true,'list'=>$list)));

}elseif ($operation == 'output') {
	
	$pcate=$_GPC["pcate"];
	$status=$_GPC["status"];
	$where= $pcate=='' ?  '' : ' and pcate='.$pcate.' ';
	$where.= $status=='0' ?  '' : ' and status='.($status-1).' ';
	$goodlist = pdo_fetchall("SELECT * FROM ".tablename('j_hmoney_goods')." WHERE weid = '{$_W['uniacid']}' and groupid='".$shopid."' $where order by id desc ");
	if(!count($goodlist))die(json_encode(array('success'=>false,'msg'=>'没有内容')));
	$category = pdo_fetchall("SELECT * FROM " . tablename('j_hmoney_goodcategory') . " WHERE weid = '{$_W['uniacid']}' and groupid='".$shopid."' order by parentid asc, displayorder asc,id desc");
	$cateAry = array();
	foreach ($category as $row) {
		$cateAry[$row['id']] = $row['title'];
	}
	$cateAry[0]="未分类";
	require_once "../framework/library/phpexcel/PHPExcel.php";
	$objPHPExcel = new PHPExcel();
	 $objPHPExcel->getProperties()->setCreator("智慧收银台")
                               ->setLastModifiedBy("智慧收银台")
                               ->setTitle("数据EXCEL导出")
                               ->setSubject("数据EXCEL导出")
                               ->setDescription("备份数据")
                               ->setKeywords("excel")
                               ->setCategory("result file");
	//条码	名称	分类	单位	销售价格	成本价格	库存
	$objPHPExcel->setActiveSheetIndex(0)
				  ->setCellValue('A1',"条码")
				  ->setCellValue('B1',"名称")
				  ->setCellValue('C1',"分类")
				  ->setCellValue('D1',"单位")
				  ->setCellValue('E1',"销售价格")
				  ->setCellValue('F1',"成本价格")
				  ->setCellValue('G1',"会员价格")
				  ->setCellValue('H1',"库存")
				  ->setCellValue('I1',"状态")
				  ->setCellValue('J1',"图片")
                  ->setCellValue('K1',"口味");
	$num=2;
	echo count($goodlist);
	foreach($goodlist as $row){
		
		$objPHPExcel->setActiveSheetIndex(0)
				  ->setCellValue('A'.$num, "'".$row['goodsn'])    
				  ->setCellValue('B'.$num, $row['title'])
				  ->setCellValue('C'.$num, $cateAry[$row['pcate']])
				  ->setCellValue('D'.$num, $row['unitname'])
				  ->setCellValue('E'.$num, $row['marketprice'])
				  ->setCellValue('F'.$num, $row['productprice'])
				  ->setCellValue('G'.$num, $row['memberprice'])
				  ->setCellValue('H'.$num, $row['store'])
				  ->setCellValue('I'.$num, $row['status'] ? "正常":"下架")
                  ->setCellValue('J'.$num, $row['thumb'])
				  ->setCellValue('K'.$num, $row['taste']);
		$num++;
	}
	
	$objPHPExcel->getActiveSheet()->setTitle('商品列表');
	$objPHPExcel->setActiveSheetIndex(0);
	ob_end_clean();
	header('Content-Type: application/vnd.ms-excel');
	header('Content-Disposition:attachment;filename="good_temp.xls"');
	header('Cache-Control:max-age=0');
	$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
	$objWriter->save('php://output');
	exit();
	
}elseif ($operation == 'insertexcel') {
	$rowid=$_GPC["rowid"];
	$rowidary=explode(",",$rowid);
	require "../framework/library/phpexcel/PHPExcel.php";
	$filePath='../attachment/j_hmoney/temp/'.$_W['uniacid']."/temp.xls";
	if(!file_exists($filePath))die(json_encode(array('success'=>false,'msg'=>"文件不存在")));
	$objPHPExcel = new PHPExcel();
	$PHPReader = new PHPExcel_Reader_Excel5(); 
	$PHPExcel = $PHPReader->load($filePath);
	$currentSheet = $PHPExcel->getSheet(0); 
	$allColumn = 11;
	$allRow = $currentSheet->getHighestRow();
	$arr = array(1 => 'A', 2 => 'B', 3 => 'C', 4 => 'D', 5 => 'E', 6 => 'F', 7 => 'G', 8 => 'H', 9 => 'I', 10 => 'J', 11 => 'K', 12 => 'L', 13 => 'M', 14 => 'N', 15 => 'O', 16 => 'P', 17 => 'Q', 18 => 'R', 19 => 'S', 20 => 'T', 21 => 'U', 22 => 'V', 23 => 'W', 24 => 'X', 25 => 'Y', 26 => 'Z');
	#条码	名称	分类	单位	销售价格	成本价格	库存	会员价格	图片 口味

    $sql="insert into ".tablename('j_hmoney_goods')." (`weid`,`groupid`,`createtime`,`goodsn`,`title`,`pcate`,`unitname`,`marketprice`,`productprice`,`store`,`memberprice`,`thumb`,`taste`,`status`) VALUES";
	$list=array();
    $updatelist=array();
	$category = pdo_fetchall("SELECT * FROM " . tablename('j_hmoney_goodcategory') . " WHERE weid = '{$_W['uniacid']}' and groupid ='".$shopid."' order by  displayorder asc, id desc");
	$categoryAry=array();
	foreach($category as $row){
		$categoryAry[$row['title']]=$row['id'];
	}
	for($currentRow = 2;$currentRow <= $allRow;$currentRow++){ 
		$realrow=$currentRow-1;
		if(!in_array($realrow,$rowidary))continue;
		$temp=array($_W['uniacid'],$shopid,TIMESTAMP);
		$rowname='';
        $updatetemp=array();
		for($column = 0; $column<$allColumn; $column++){
			$val = $currentSheet->getCellByColumnAndRow($column,$currentRow)->getValue();
			if($column == 0){
                if(!$val || strlen($val)<2)continue;
                $rowname=trim($val);
            }
			if($column == 2)$val= intval($categoryAry[trim($val)]);
			if($column == 4 || $column == 5 || $column == 7)$val=$this->_2money($val*100);
            if($column == 10){
                $val= $val=="上架" ? 1 : 0;
            }
			array_push($temp,strval($val));
            array_push($updatetemp,strval($val));
		}
        $updatelist[$rowname]=$updatetemp;
		$list[$rowname]="('".implode("','",$temp)."')";
	}
	$cardnoAry=array_keys($list);
	$inList = pdo_fetchall("SELECT goodsn,id FROM ".tablename('j_hmoney_goods')." WHERE weid = '{$_W['uniacid']}' and groupid='".$shopid."' and  goodsn in('".implode("','",$cardnoAry)."') ");
	if($inList){
		foreach($inList as $row){
			$temprow=$updatelist[$row['goodsn']];
			$data=array();
			if(trim($temprow[1]))$data['title']=$temprow[1];
			if(trim($temprow[3]))$data['unitname']=$temprow[3];
			if(trim($temprow[4]))$data['marketprice']=$temprow[4];
			if(trim($temprow[5]))$data['productprice']=$temprow[5];
			if(trim($temprow[6]))$data['store']=$temprow[6];
			if(trim($temprow[7]))$data['memberprice']=$temprow[7];
			if(trim($temprow[8]))$data['thumb']=$temprow[8];
            if(trim($temprow[9]))$data['taste']=$temprow[9];
            $data['status']=$temprow[10];
			if(count($data))pdo_update('j_hmoney_goods',$data,array("id"=>$row['id']));
			unset($list[$row['goodsn']]);
		}
	}

    if(count($list))$result=pdo_run($sql.implode(",",$list));
	die(json_encode(array('success'=>true,"num"=>count($list),"num1"=>count($inList),"result"=>$result)));
	
}elseif ($operation == 'deallost') {
	$idary=$_GPC['idary'];
	pdo_update("j_hmoney_membercard",array("status"=>2)," id in (".$idary.")");
	die(json_encode(array('success'=>true)));
	
}elseif ($operation == 'printdisplay') {
	$list = pdo_fetchall("SELECT * FROM ".tablename('j_hmoney_cookprint')." WHERE weid = '{$_W['uniacid']}' and groupid='".$shopid."' order by id desc ");
	
}elseif ($operation == 'printpost') {
	$id=$_GPC['id'];
	if($id){
		$item = pdo_fetch("SELECT * FROM ".tablename('j_hmoney_cookprint')." WHERE  id=:a ",array(":a"=>$id));
	}
	
}elseif ($operation == 'printpostdata') {
	$id = intval($_GPC['id']);
	$param=array();
	if($_GPC['param-key']){
		foreach($_GPC['param-key'] as $index=>$row){
			$param[$row]=$_GPC['param-val'][$index];
		}
	}
	$data = array(
		'weid' => $_W['uniacid'], 
		'title' => $_GPC['title'], 
		'groupid' => intval($shopid),
		'ptype' => intval($_GPC['ptype']),
		'param' => json_encode($param),
	);
	if (!empty($id)) {
		pdo_update('j_hmoney_cookprint', $data, array('id' => $id));
	} else {
		pdo_insert('j_hmoney_cookprint', $data);
	}
	die(json_encode(array("success"=>true)));

}elseif ($operation == 'printdelete') {
	$id=$_GPC['id'];
	if($id){
		pdo_delete("j_hmoney_cookprint",array("id"=>$id));
	}
	message("删除成功",$this->createWebUrl("goods",array('op'=>'printdisplay')),"success");
	
}elseif ($operation == 'changecooker') {
	$idAry=$_GPC['goodid'];
	$cookid=$_GPC['pcate'];
	if(count($idAry)==0)die(json_encode(array('success'=>false,'msg'=>"请选择商品")));
	pdo_update('j_hmoney_goods', array("cooker"=>$cookid), " id in (".implode(",",$idAry).")");
	die(json_encode(array('success'=>true)));
	
}elseif ($operation == 'changepcatecooker'){
	$pcate=$_GPC['pcate'];
	$cookid=$_GPC['cookid'];
	pdo_update('j_hmoney_goods', array("cooker"=>$cookid), array("pcate"=>$pcate));
	die(json_encode(array('success'=>true)));


}
include $this->template('web/'.$cfg['floder'].'/goods');